#include "device_ds18b20.h"
#include "log.h"

void DS18B20Control::init()
{
    m_onewire.begin(DS18B20_PIN);
    m_ds18b20Ctl = new DallasTemperature(&m_onewire);
    m_ds18b20Ctl->begin();
    // 初始化温度采集器
    m_tempCollector = new Ticker();
    m_tempCollector->attach_ms(TEMP_COLLECT_INTERVAL, [this](){ readTempCallback(); });
}

void DS18B20Control::readTempCallback()
{
    // 请求温度数据
    m_ds18b20Ctl->requestTemperatures();
    // 获取第一个传感器的温度
    float_t temperature = m_ds18b20Ctl->getTempCByIndex(0);
    m_temperature = temperature;
    LOG_DEBUG("temperature:" + String(temperature) + "C");
}

DS18B20Control::~DS18B20Control()
{
    if (m_tempCollector != nullptr) {
        delete m_tempCollector;
    }
    if (m_ds18b20Ctl != nullptr) {
        delete m_ds18b20Ctl;
    }
}